<route lang="json5">
{
  style: {
    navigationBarTitleText: '录入快递',
  },
}
</route>

<template>
  <view class="container">
    <!-- 步骤一：输入手机号 -->
    <view v-if="step === 1">
      <view class="card">
        <!-- <view class="info-item">
          <text class="info-label">快递公司</text>
          <text class="info-value">{{ companyName }}</text>
        </view> -->
        <view class="info-item">
          <text class="info-label">快递单号</text>
          <text class="info-value">{{ orderId }}</text>
        </view>
      </view>

      <view class="phone-section">
        <view class="phone-title">输入收件人手机号后4位</view>
        <view class="phone-input-group">
          <input
            v-for="(digit, idx) in 4"
            :key="idx"
            class="phone-digit"
            maxlength="1"
            type="number"
            v-model="phoneDigits[idx]"
            @input="onDigitInput(idx)"
            :focus="idx === currentFocusIndex"
            @keyup.delete="handleDelete(idx)"
          />
        </view>
      </view>

      <button class="submit-btn" @click="handleFirstStep">确定</button>
    </view>

    <!-- 步骤二：确认地址 -->
    <view v-else class="confirm-page">
      <view class="card">
        <view class="express-info">
          <!-- <view class="info-item">
            <text class="info-label">快递公司</text>
            <text class="info-value">{{ companyName }}</text>
          </view> -->
          <view class="info-item">
            <text class="info-label">快递单号</text>
            <text class="info-value">{{ orderId }}</text>
          </view>
        </view>

        <view class="divider"></view>

        <view v-if="addressList.length > 0" class="address-title">选择与快递单一致的地址</view>
        <radio-group class="address-list" @change="onAddressChange" v-if="addressList.length > 0">
          <label v-for="(item, index) in addressList" :key="index" class="address-item">
            <radio
              :value="index.toString()"
              :checked="selectedAddressIndex === index"
              color="#8b5cf6"
            />
            <view class="address-content">
              <view class="address-phone">{{ item.nickname }}:{{ item.mobile }}</view>
              <view class="address-name">{{ item.name }}{{ item.building }}{{ item.floor }}</view>

              <view class="address-text">{{ item.address }}</view>
            </view>
          </label>
        </radio-group>
        <view class="empty-address" v-else>
          <text>暂无用户</text>
        </view>
      </view>

      <button v-if="addressList.length > 0" class="submit-btn" @click="handleSubmit">确定</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getRechargeList1, enterOrder } from '@/service/index/foo'

// 这些数据应该从页面参数或上一页传递过来
const companyName = ref('中通快递')
const orderId = ref('4002323322332')
const step = ref(1)
const phoneDigits = ref(['', '', '', ''])
const addressList = ref<any[]>([])
const selectedAddressIndex = ref(0)
const currentFocusIndex = ref(0)

// 处理手机号输入
const onDigitInput = (idx: number) => {
  if (phoneDigits.value[idx].length === 1 && idx < 3) {
    // Force next input focus
    currentFocusIndex.value = idx + 1
    // Focus after reactivity updates
    setTimeout(() => {
      const inputs = uni.createSelectorQuery().selectAll('.phone-digit')
      inputs
        .boundingClientRect((rects: any) => {
          if (rects && rects[idx + 1]) {
            rects[idx + 1].focus()
          }
        })
        .exec()
    }, 50)
  }
}

// Handle backspace/delete
const handleDelete = (idx: number) => {
  if (phoneDigits.value[idx] === '' && idx > 0) {
    phoneDigits.value[idx - 1] = ''
    currentFocusIndex.value = idx - 1

    setTimeout(() => {
      const inputs = uni.createSelectorQuery().selectAll('.phone-digit')
      inputs
        .boundingClientRect((rects: any) => {
          if (rects && rects[idx - 1]) {
            rects[idx - 1].focus()
          }
        })
        .exec()
    }, 50)
  }
}

onLoad((param) => {
  orderId.value = param.code
})
// 处理地址选择
const onAddressChange = (e: any) => {
  selectedAddressIndex.value = Number(e.detail.value)
}

// 第一步确认
const handleFirstStep = async () => {
  if (phoneDigits.value.some((d) => !d)) {
    uni.showToast({ title: '请输入手机号后4位', icon: 'none' })
    return
  }
  const res = await getRechargeList1({ mobile: phoneDigits.value.join('') })
  console.log(res)
  addressList.value = res.data

  step.value = 2
}

// 最终提交
const handleSubmit = async () => {
  try {
    if (addressList.value.length === 0) {
      uni.showToast({ title: '没有可选择的地址', icon: 'none' })
      return
    }

    const selected = addressList.value[selectedAddressIndex.value]
    if (!selected) {
      uni.showToast({ title: '请选择地址', icon: 'none' })
      return
    }

    const res = await enterOrder({
      cabinet_code: selected.cabinet_code,
      member_id: selected.member_id,
      name: selected.name,
      express_no: orderId.value,
    })

    if (res.code === 0) {
      uni.showToast({ title: '录入成功', icon: 'success' })
      // 这里可以选择重置表单或返回上一页
      setTimeout(() => {
        uni.reLaunch({ url: '/pages/scan/index' })
      }, 1500)
    } else {
      uni.showToast({ title: res.data, icon: 'none' })
    }
  } catch (error: any) {
    uni.showToast({
      title: error?.data,
      icon: 'none',
    })
  }
}
</script>

<style>
.container {
  min-height: 100vh;
  padding: 20px;
  background: #f5f5f5;
}

.card {
  padding: 16px;
  margin-bottom: 20px;
  background: #fff;
  border-radius: 12px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-label {
  width: 80px;
  font-size: 15px;
  color: #666;
}

.info-value {
  flex: 1;
  font-size: 15px;
}

.phone-section {
  margin: 24px 0;
}

.phone-title {
  margin-bottom: 16px;
  font-size: 14px;
  color: #666;
  text-align: center;
}

.phone-input-group {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.phone-digit {
  width: 40px;
  height: 40px;
  font-size: 18px;
  text-align: center;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.submit-btn {
  width: 80%;
  height: 44px;
  margin-top: 32px;
  font-size: 16px;
  color: #fff;
  background: #8b5cf6;
  border-radius: 22px;
}

.submit-btn:active {
  background: #7c3aed;
}

.divider {
  height: 1px;
  margin: 16px 0;
  background: #eee;
}

.address-title {
  margin-bottom: 16px;
  font-size: 14px;
  color: #666;
}

.address-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.address-item {
  display: flex;
  align-items: flex-start;
  padding: 12px;
  background: #f8f8f8;
  border-radius: 8px;
}

.address-content {
  flex: 1;
  margin-left: 8px;
}

.address-name {
  margin-bottom: 4px;
  font-size: 16px;
}

.address-phone {
  margin-bottom: 4px;
  font-size: 14px;
  color: #666;
}

.address-text {
  font-size: 14px;
  color: #666;
}

.empty-address {
  padding: 20px 0;
  font-size: 14px;
  color: #666;
  text-align: center;
  background: #f8f8f8;
  border-radius: 8px;
}
</style>
